<template>
  <div class="container">
    <Breadcrumb :items="['menu.list', '资产地图']" />
    <a-card class="general-card" title="资产地图">
      <!-- 地图容器：用 ref 绑定 -->
      <div class="map-container" ref="mapRef"></div>
    </a-card>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import { useRouter, useRoute } from 'vue-router';
const router = useRouter();
const route = useRoute();
const {} = route.query;
const state = reactive({});
// 地图 DOM 引用
const mapRef = ref<HTMLDivElement | null>(null);
let map: any = null;

// 动态加载脚本工具，避免重复加载
const loadedScripts = new Set<string>();
function loadScript(src: string): Promise<void> {
  return new Promise((resolve, reject) => {
    if (loadedScripts.has(src)) return resolve();
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = src;
    script.onload = () => {
      loadedScripts.add(src);
      resolve();
    };
    script.onerror = (e) => reject(e);
    document.head.appendChild(script);
  });
}

// 定义全局跳转函数，供 InfoWindow 内联 onclick 调用
(window as any).__goAssetDetail = (id: string) => {
  console.log(id);
  router.push({ path: 'assetsDetail', query: { type: 'look', id } });
};

async function inits() {
  const AMAP_KEY =
    import.meta.env.VITE_AMAP_KEY || '77a7c37b7c94ea24032824d3149aa7d2';
  // 加载高德地图 JS API 和 UI 插件（与 index.html 保持一致版本）
  await loadScript(`https://webapi.amap.com/maps?v=1.4.15&key=${AMAP_KEY}`);
  await loadScript('https://webapi.amap.com/ui/1.0/main.js?v=1.0.11');

  const AMap = (window as any).AMap;
  if (!AMap || !mapRef.value) return;

  // 初始化地图：默认使用卫星图，且不叠加路网与路况
  map = new AMap.Map(mapRef.value, {
    resizeEnable: true,
    viewMode: '3D',
    zoom: 13,
    center: [116.397428, 39.90923],
    layers: [
      new AMap.TileLayer.Satellite(), // 仅卫星图
      // 不添加 RoadNet / Traffic 图层，默认不显示路网/路况
    ],
    // 如果后续切到矢量底图，也尽量隐藏路网元素
    // features: ['bg', 'point'], // 不包含 'road'
  });

       // 添加工具条与图层切换控件：默认卫星，且卫星图不显示路网
  AMap.plugin(['AMap.ToolBar', 'AMap.MapType'], function () {
    const toolBar = new AMap.ToolBar({
      position: 'LT',
      offset: new AMap.Pixel(10, 10),
    });
    map.addControl(toolBar);

    const mapType = new AMap.MapType({
      defaultType: 1, // 1: 卫星图为默认
      showRoad: false, // 卫星图下不显示路网叠加
      position: 'RT',
    });
    map.addControl(mapType);
  });

  // 生成10个标记点，红/黄/绿循环
  const colors = ['red', 'yellow', 'green'];
  const markers: any[] = [];
  const infoWindows: any[] = [];

  for (let i = 0; i < 10; i++) {
    const lng = 116.3 + Math.random() * 0.2;
    const lat = 39.9 + Math.random() * 0.2;
    const color = colors[i % 3];
    const assetId = `FT${11233 + i}`; // 示例ID，可替换为真实数据

    const marker = new AMap.Marker({
      position: [lng, lat],
      icon: new AMap.Icon({
        size: new AMap.Size(20, 20),
        image: `data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="${color}"><circle cx="12" cy="12" r="10" stroke="black" stroke-width="1"/></svg>`,
        imageSize: new AMap.Size(20, 20),
      }),
      offset: new AMap.Pixel(-10, -10),
      title: `标记点${i + 1}`,
    });

    marker.setMap(map);
    markers.push(marker);

    const infoWindow = new AMap.InfoWindow({
      content: `<div class="custom-info-window" style="color:#fff;">
                    <h3>资产详细信息</h3>
                    <p>ID：${assetId}</p>
                    <p>尺寸：75寸</p>
                    <p>位置: [${lng.toFixed(6)}, ${lat.toFixed(6)}]</p>
                    <p>资产类型：显示器</p>
                    <p class="detail-link" onclick="window.__goAssetDetail('${assetId}')">详情 &gt; </p>
                  </div>`,
      offset: new AMap.Pixel(0, -30),
    });
    infoWindows.push(infoWindow);

    marker.on('click', () => {
      infoWindow.open(map, marker.getPosition());
    });
  }

  // 自动适配视野
  map.setFitView();
}

onMounted(() => {
  inits();
});
</script>
<style lang="less" scoped>
    .map-container {
    // min-height: 500px;
    width: 100%;
    height: calc(100vh - 280px);
    }


/* 参考 index.html 的信息窗体样式 */
:deep(.custom-info-window) {
  color: #fff;
}

.custom-info-window p {
  color: white;
  margin: 5px 0;
}

:deep(.amap-info-content) {
  background-color: #1a365d;
  border-radius: 24px;
  border: 2px solid #2b6cb0;
}

:deep(.amap-popup-content) {
  padding: 10px;
}

:deep(.detail-link) {
  cursor: pointer;
  text-decoration: underline;
}
</style>
